"""
Case Type   : CBM
Case Name   : 对CBM新增参数cbm_xlog_files_epoch合理取值验证
Create At   : 2025/4
Owner       : songshixuan
Description :
    1、查看参数默认值
    2、alter system方式修改参数值为边界值1
    3、gs_guc set方式修改参数值为边界值16
    4、修改参数值为非边界值的正常值
    5、恢复默认值
Expect      :
    1、参数默认值为1
    2、修改成功
    3、修改成功
    4、修改成功
    5、恢复默认值成功
History     :
    1、2025-04-07 创建
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SharedStorage(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()

        self.param = 'cbm_xlog_files_epoch'

    def test_shared_storage(self):
        text = '-----step1:查看参数默认值;  expect:参数默认值为1-----'
        self.log.info(text)

        value = self.pri_sh.execut_db_sql(f'show {self.param}', dbname='postgres')
        self.param_default = value.splitlines()[-2].strip()
        self.log.info(self.param_default)
        self.assertEqual('1', self.param_default, '参数默认值校验失败')

        text = '-----step2:alter system方式修改参数值为边界值1;  expect:修改成功-----'
        self.log.info(text)

        value = self.pri_sh.execut_db_sql(f"alter system set {self.param} to 1;", dbname='postgres')
        self.log.info(value)
        self.assertIn(self.constant.ALTER_SYSTEM_SUCCESS_MSG, value, '修改失败')

        text = '-----step3:gs_guc set方式修改参数值为边界值16;  expect:修改成功-----'
        self.log.info(text)

        value = self.pri_sh.execute_gsguc('set',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f"{self.param} = 16")
        self.log.info(value)
        self.assertTrue(value, '修改失败')

        text = '-----step4:修改参数值为非边界值的正常值;  expect:修改成功-----'
        self.log.info(text)

        value = self.pri_sh.execute_gsguc('set',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f"{self.param} = 6")
        self.log.info(value)
        self.assertTrue(value, '修改失败')

    def tearDown(self):
        text = '-----step5:恢复初始环境参数默认值  expect:恢复成功-----'
        self.log.info(text)

        reset_param = self.pri_sh.execute_gsguc('set',
                                                self.constant.GSGUC_SUCCESS_MSG,
                                                f'{self.param} = {self.param_default}')
        self.log.info(reset_param)

        restart = self.pri_sh.restart_db_cluster()
        self.log.info(restart)

        value = self.pri_sh.execut_db_sql(f'show {self.param}', dbname='postgres')
        self.log.info(value)
        self.assertEqual(self.param_default, value.splitlines()[-2].strip(), '恢复默认值失败')
        self.assertTrue(restart)
        self.log.info(f'----{os.path.basename(__file__)} end----')
